package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.MemberElderDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IFamilyMemberElderService familyMemberElderService;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of("生活更美好", "大桔大利", "日富一日", "好柿开花", "柿柿如意", "一椰暴富", "大柚所为", "杨梅吐气", "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if (ObjectUtil.isEmpty(familyMember)) {
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder().openId(openid).build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember, phone);

        //6. 把用户的信息封装到token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", familyMember.getName());
        claims.put("userId", familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     * 新增或修改用户
     *
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int) (Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index) + phone.substring(phone.length() - 4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 绑定老人
     *
     * @param memberElderDto
     * @return
     */
    @Override
    public void add(MemberElderDto memberElderDto) {
        // 1. 根据身份证号查询老人信息
        if (ObjectUtil.isEmpty(memberElderDto)) {
            throw new BaseException("输入信息不能为空");
        }
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, memberElderDto.getIdCard()).one();
        // 2. 判断老人是否存在和入住状态 都符合 获取老人id
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("未找到老人！");
        }
        if (elder.getStatus() != 1) {
            throw new BaseException("老人未入住！");
        }
        Long elderId = elder.getId();
        // 3. 获取家属id 从ThreadLocal中获取
        Long familyMemberId = UserThreadLocal.getUserId();
        // 4. 封装对象 向家人老人关系表中添加数据
        FamilyMemberElder familyMemberElder = FamilyMemberElder.builder().elderId(elderId).familyMemberId(familyMemberId).build();
        familyMemberElder.setRemark(memberElderDto.getRemark());
        familyMemberElderService.save(familyMemberElder);
    }

    /**
     * 查询家人列表 用于预约模块
     *
     * @return
     */
    @Override
    public List<ElderBindVo> queryElderBindList() {
        // 1. 获取当前登录的家人id
        Long familyMemberId = UserThreadLocal.getUserId();
        // 2. 根据家人id查询家人信息
        List<FamilyMemberElder> familyMemberElderList = familyMemberElderService.lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, familyMemberId).list();
        // 3. 判断老人-家人信息是否为空
        if (ObjectUtil.isEmpty(familyMemberElderList)) {
            return Collections.emptyList();
        }
        // 4. 遍历老人-家属信息集合 获取老人姓名
        Set<Long> elderIdSet = familyMemberElderList.stream().map(FamilyMemberElder::getElderId).collect(Collectors.toSet());
        List<Elder> elderList = elderService.lambdaQuery().in(Elder::getId, elderIdSet).list();
        Map<Long, String> elderIdNameMap = elderList.stream().collect(Collectors.toMap(Elder::getId, Elder::getName));
        // 4. 封装结果 返回
        List<ElderBindVo> bindVoList = BeanUtil.copyToList(familyMemberElderList, ElderBindVo.class);
        bindVoList.forEach(bindVo -> bindVo.setElderName(elderIdNameMap.get(bindVo.getElderId())));
        return bindVoList;
    }


    /**
     * 查看已绑定家人列表（分页查询）
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MemberElderVo> pageQueryBindedElder(Integer pageNum, Integer pageSize) {
        // 1. 从ThreadLocal中 获取当前登录用户id(familyMemberId)
        Long familyMemberId = UserThreadLocal.getUserId();

        // 2. 获取要返回给前端的信息
        // 通过familyMemberId查询 家人-老人关系表 查询绑定的所有老人
        // 通过elderId查询老人信息
        // 通过bedId查询床位信息=> 获取房间id => 获取房间类型名称
        // 通过老人id 设备位置类型 物理位置类型 查询物联网设备信息
        PageHelper.startPage(pageNum, pageSize);
        List<MemberElderVo> memberElderVoList = familyMemberElderMapper.pageQueryBindedElder(familyMemberId);
        Page<MemberElderVo> memberElderVoPage = (Page<MemberElderVo>) memberElderVoList;
        // 3. 返回
        return memberElderVoPage.getResult();
    }

    /**
     * 查询设备健康数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        // 1. 从redis中获取设备数据
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        List<DeviceData> deviceDataList = (List<DeviceData>) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        if (ObjectUtil.isNotEmpty(deviceDataList)) {
            deviceDataList.forEach(deviceData -> {
                DeviceDataVo deviceDataVo = DeviceDataVo.builder()
                        .functionId(deviceData.getFunctionId())
                        .value(deviceData.getDataValue())
                        .eventTime(deviceData.getAlarmTime().toString())
                        .build();
                deviceDataVoList.add(deviceDataVo);
            });
        }
        return deviceDataVoList;
    }

    /**
     * 解绑老人
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        familyMemberElderService.lambdaUpdate()
                .eq(FamilyMemberElder::getId, id)
                .remove();
    }

    /**
     * 按天统计查询指标数据
     *
     * @param iotId
     * @param functionId
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByDay(String iotId,
                                                            String functionId,
                                                            Long start,
                                                            Long end) {
        // 1. 获取开始时间和结束时间
        LocalDateTime startTime = DateUtil.date(start).toLocalDateTime();
        LocalDateTime endTime = DateUtil.date(end).toLocalDateTime();
        // 2. 24小时的统计数据示例
        List<DeviceDataGraphVo> deviceDataGraphVos = DeviceDataGraphVo.dayInstance(startTime);
        List<DeviceDataGraphVo> deviceDataGraphVosDB = deviceDataMapper.queryDeviceDataListByDay(iotId, functionId, startTime, endTime);
        // 3. 遍历数据库查询结果 补全查到的值
        if (ObjectUtil.isNotEmpty(deviceDataGraphVosDB)) {
            deviceDataGraphVos.forEach(deviceDataGraphVo -> {
                deviceDataGraphVosDB.forEach(deviceDataGraphVoDB -> {
                    if (deviceDataGraphVo.getDateTime().equals(deviceDataGraphVoDB.getDateTime())) {
                        deviceDataGraphVo.setDataValue(deviceDataGraphVoDB.getDataValue());
                    }
                });
            });
        }
        return deviceDataGraphVos;
    }

    /**
     * 按周统计查询指标数据
     *
     * @param iotId
     * @param functionId
     * @param start
     * @param start
     * @return
     */
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByWeek(String iotId, String functionId, Long start, Long end) {
        // 1. 获取开始时间和结束时间
        LocalDateTime startTime = DateUtil.date(start).toLocalDateTime();
        LocalDateTime endTime = DateUtil.date(end).toLocalDateTime();
        // 2. 一周七天的统计数据示例
        List<DeviceDataGraphVo> deviceDataGraphVos = DeviceDataGraphVo.weekInstance(startTime);
        List<DeviceDataGraphVo> deviceDataGraphVosDB = deviceDataMapper.queryDeviceDataListByWeek(iotId, functionId, startTime, endTime);
        // 3. 遍历数据库查询结果 补全查到的值
        if (ObjectUtil.isNotEmpty(deviceDataGraphVosDB)) {
            deviceDataGraphVos.forEach(deviceDataGraphVo -> {
                deviceDataGraphVosDB.forEach(deviceDataGraphVoDB -> {
                    if (deviceDataGraphVo.getDateTime().equals(deviceDataGraphVoDB.getDateTime())) {
                        deviceDataGraphVo.setDataValue(deviceDataGraphVoDB.getDataValue());
                    }
                });
            });
        }
        return deviceDataGraphVos;
    }


}
